﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.BLL;
using ECCIT;
using ECCIT.Security;

public partial class UKNOW_member_register : System.Web.UI.Page
{
    private  string PageConfigXML = @"XML\PageConfig.xml";
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
   

    /// <summary>
    /// 判断该用户是否存在
    /// </summary>
    /// <returns></returns>
    private bool ExistsUser()
    { 
        bool isExist=false;
        string username=tbxUserName.Text;
        if (!string.IsNullOrEmpty(username))
        {
            if (!string.IsNullOrEmpty(username))
                if (new MemberBLL(2052).Check(username) == null)
            {
                return isExist=true;
            }
        }
        return isExist;
    }

    /// <summary>
    /// 判断邮箱是否存在
    /// </summary>
    /// <returns></returns>
    private bool ExistsMail()
    {
        bool isExist=false;
        string email = tbxUserMail.Text;

        if (!string.IsNullOrEmpty(email))
        {
            if(new MemberBLL(2052).CheckEmail(email).Count==0)
            {
                return isExist=false;
            }
        }
       
        return isExist=true;
    }

    protected void lbRegister_Click(object sender, EventArgs e)
    {
       
        if (tbxUserName.Text!=""&& tbxUserName.Text.Length>3)
        {
            Register(); 
        }
        
    }


    /// <summary>
    /// 邮件验证
    /// </summary>
    /// <returns></returns>
    private bool ValidateEmail()
    {
        bool isvalid = true;
        string email = tbxUserMail.Text;
        if (!string.IsNullOrEmpty(email)&&(email!=hideMail.Value))
        {
            string strRegex = @"^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$";
            Regex re = new Regex(strRegex);
            if (!re.IsMatch(email))
            {
                isvalid = false;
                ScriptManager.RegisterClientScriptBlock(Page, GetType(), "MailError", @"$(function () { $('#errorEmail').find('span').empty(); $('#errorEmail').show().append('<span>请输入电子邮件地址</span>'); });", true);
            }


        }
        else
        {
            isvalid = false;
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "MailIsNull", @"$(function () { $('#errorEmail').find('span').empty(); $('#errorEmail').show().append('<span>请输入有效的电子邮件地址</span>'); });", true);
        }

        return isvalid;
    }

    /// <summary>
    /// 手机及电话号码验证
    /// </summary>
    /// <returns></returns>
    private bool ValidateMobile()
    {
        bool isvalid = true;

        string mobile = tbxPhone.Text;
        if (!string.IsNullOrEmpty(mobile)&&(mobile!=hidePhoneNum.Value))
        {
            string strRegex = @"^1[3|4|5|8][0-9]\d{4,8}$";
            string strTel = @"^\d{3,4}-?\d{7,9}$";
            Regex re = new Regex(strRegex);
            Regex reTel = new Regex(strTel);
            if ((re.IsMatch(mobile)) || (reTel.IsMatch(mobile)))
            {
                isvalid = true;
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(Page, GetType(), "PhoneError", @"$(function () { $('#errorMobile').find('span').empty();$('#errorMobile').show().append('<span>无效的手机号码,请重试</span>'); });", true);
                isvalid = false;
            }

        }
        else
        {
            tbxPhone.Text = "";
            
        }

        return isvalid;
    }


    /// <summary>
    /// registerType:1  中文注册
    /// registerType:0  英文注册
    /// </summary>
    /// <param name="registerType"></param>
    private void Register()
    {
        //string registerType = "1";
        string checkCode = (string)Context.Session["CheckCode"];
        string errMsg = string.Empty;

        if (ExistsUser())
        {
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "UserExits", @"$(function () 
            {$('#errorUserName').find('span').empty();
            $('#errorUserName').show().append('<span>该用户已经存在</span>');
            $('#imageUserNameInfo').show().attr('src', 'images/UK_icon06.gif');
            });", true);
            return;
        }

        if (ExistsMail())
        {

            string email = tbxUserMail.Text;
            if (string.IsNullOrEmpty(email))
            {
                ScriptManager.RegisterClientScriptBlock(Page, GetType(), "MailError", @"$(function () { $('#errorEmail').find('span').empty(); $('#errorEmail').show().append('<span>请填写你的邮箱</span>'); });", true);
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(Page, GetType(), "MailError", @"$(function () { $('#errorEmail').find('span').empty(); $('#errorEmail').show().append('<span>邮箱已存在</span>'); });", true);
            }
            return;
        }

        if (!ValidateEmail())
        {
            return;
        }
        //if (!ValidateMobile())
        //{
        //    return;
        //}
        if (tbxCheckCode.Text.Trim().ToUpper() == checkCode)
        {
            if (tbxPwd.Text.Trim() == tbxConfimPwd.Text.Trim())
            {
                if (cbxAgreed.Checked)
                {
                   MemberModel model = GetUserInfo();
                   ResultInfo res = new MemberBLL(2052).Save(model);
                    if (res.Result)
                    {
                        //创建session
                        AccountController ac = new AccountController(2052);
                        ac.AccountInfo = model;
                        
                       
                        //注册成功
                        ScriptManager.RegisterClientScriptBlock(Page, GetType(), "sucess", @"alert('您的UK NOW账户已经创建。 感谢您的注册!'); location.href='/cn/home.html';", true);


                      
                        
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, GetType(), "register failed", "alert('注册失败,请重试')", true);
                        
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, GetType(), "agreement", "$(function () { $('#divAgreed').show();});", true);
                     
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(Page, GetType(), "confimPwd", @"$(function () {$('#errorConfimPwd').show().append('<span>两次输入密码不匹配. 请重试</span>'); });", true);
            }
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(Page, GetType(), "VerifyCode", @"$(function () { $('#errorCode').find('span').empty();$('#errorCode').show().append('<span>你输入的验证码不匹配,请重试</span>'); });", true);
        }
    }
    /// <summary>
    /// 获取用户对象信息
    /// </summary>
    /// <returns></returns>
    public MemberModel GetUserInfo()
    {
        MemberModel model = new MemberModel();
        
        model.LastLoginTime = DateTime.Now;//上次登录时间
        model.Name = tbxUserName.Text;
        model.Password = MD5Crypto.GetMD5Hash(tbxPwd.Text);
        model.Mobile= tbxPhone.Text;
        model.Email = tbxUserMail.Text;
        model.StudyAbroad=GetCbxStatus(cbxStudy);
        model.IELTS=GetCbxStatus(cbxIELTS);
        model.ArtsAndCulture = GetCbxStatus(cbxArts);
        model.Sina = GetCbxStatus(cbxSina);
        model.Sohu = GetCbxStatus(cbxSohu);
        model.TengXun = GetCbxStatus(cbxTengxun);
        model.SinaWeibo = GetCbxStatus(cbxSinaWeibo);
        model.TengXunWeibo = GetCbxStatus(cbxTengxunWeibo);
        model.KaiXin = GetCbxStatus(cbxKaixin);
        model.DouBan = GetCbxStatus(cbxDouban);
        model.RenRen = GetCbxStatus(cbxRenren);
        model.Google = GetCbxStatus(cbxGoogle);
        model.Baidu = GetCbxStatus(cbxBaidu);
        model.Bing = GetCbxStatus(cbxBing);
        model.OfflineEvents = GetCbxStatus(cbxOfflineEvents);
        model.NewsPaper = GetCbxStatus(cbxNewspaper);
        model.Outdoor = GetCbxStatus(cbxOutdoor);
        model.Taxi = GetCbxStatus(cbxTaxi);
        model.Metro = GetCbxStatus(cbxMetro);
        model.TV = GetCbxStatus(cbxTV);
        model.BBS =GetCbxStatus(cbxBBS);
        model.Recommendation = GetCbxStatus(cbxRecommendtion);
        model.InsertTime = DateTime.Now;
        model.MemberImg = HeadImg.Text + ".jpg";
        
        return model;
    }

    private string GetCbxStatus(HtmlInputCheckBox cbx)
    {
        return cbx.Checked ? "Y" : "N";
    }

    ///// <summary>
    ///// 获得当前Session里保存的标志
    ///// </summary>
    ///// <returns></returns>
    //public string GetToken()
    //{
    //    if (null != Session["Token"])
    //    {
    //        return Session["Token"].ToString();
    //    }
    //    else
    //    {
    //        return string.Empty;
    //    }
    //}


    ///// <summary>
    ///// /生成标志，并保存到Session
    ///// </summary>
    //private void SetToken()
    //{

    //    Session.Add("Token", MD5.GetMD5(Session.SessionID + DateTime.Now.Ticks.ToString()));
    //}

}
